<?php


namespace app\api\logic;


use app\model\order\Order;
use app\model\order\OrderRefund;
use support\exception\BadException;
use support\utils\Time;

class OrderRefundLogic extends \app\admin\order\logic\OrderRefundLogic
{
    public function apply($input)
    {
        $order = Order::where([
            "id" => $input['order_id'],
            "order_no" => $input['order_no'],
        ])
            ->field([
                'status',
                'refund_status',
            ])->find();
        if (!$order) {
            throw new BadException("订单不存在");
        }
        if ($order["status"] <= Order::STATUS_WAIT_PAID || $order["refund_status"] != Order::REFUND_STATUS_NORMAL) {
            throw new BadException("订单状态已改变,请稍后重试");
        }

        OrderRefund::insert([
            "order_id" => $input['order_id'],
            "order_type" => $input['order_type'],
            "order_no" => $input['order_no'],
            "refund_order_no" => "R" . date("YmdHis") . str_pad(rand(0, 9999), 4, '0'),
            "user_id" => request()->uid,
            "user_name" => "",
            "step" => "",
            "refund_type" => 1,
            "refund_way" => 1,
            "refund_num" => array_sum(array_column($input['apply_refund_data'], 'num')),
            "refund_price" => $input['refund_price'],
            "refunded_price" => "",
            "apply_refund_reason" => $input['apply_refund_reason'],
            "refund_img" => json_encode($input['refund_img'] ?? []),
            "remark" => $input['remark'] ?? "",
            "apply_refund_data" => json_encode($input['apply_refund_data']),
            "create_time" => Time::now(),
            "update_time" => Time::now(),
        ]);

        Order::update([
            'refund_status' => Order::REFUND_STATUS_REVIEW_ING
        ], [
            "id" => $input['order_id'],
            "order_no" => $input['order_no'],
            'refund_status' => Order::REFUND_STATUS_NORMAL
        ]);
    }

}